package com.yjha.lzmarathonsys.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yjha.lzmarathonsys.utils.JwtUtils;
import com.yjha.lzmarathonsys.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 进入controller层之前拦截请求
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String url = request.getRequestURI();
        String token = JwtUtils.getTokenFromRequest(request);
        String openId = JwtUtils.getOpenId(token);
        if("OPTIONS".equals(request.getMethod())) {return true;}
        response.setCharacterEncoding("utf-8");
        if(openId!=null){
            // 对前台请求进行 token 验证
            if (StrUtil.isBlank(token)) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error((short) 401, "请求失败！令牌不能为空！")));
                return false;
            }

            try {
                JwtUtils.verifyToken(token);
            } catch (Exception e) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error((short) 401, "请求失败！令牌无效或已过期！")));
                return false;
            }
        }else{
            // 处理后台请求（可以直接通过，不限制 URL 或者通过其他逻辑检查）
            if (StrUtil.isBlank(token)) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error((short) 401, "请求失败！令牌不能为空！")));
                return false;
            }
            try {
                JwtUtils.verifyToken(token);
            } catch (Exception e) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error((short) 401, "请求失败！令牌无效或已过期！")));
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //        System.out.println("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //        System.out.println("---------------视图渲染之后的操作-------------------------");
    }
}

